package com.mycase.im.boot.websocket.pattern.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mycase.im.boot.entity.communication.ClientMessage;
import com.mycase.im.boot.entity.communication.ResponseMessage;
import com.mycase.im.boot.service.GroupMessageBodyService;
import com.mycase.im.boot.service.MessageService;
import com.mycase.im.boot.websocket.WebSocketSignal;
import com.mycase.im.boot.websocket.pattern.MessageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.Map;

/**
 * 用来处理消息未读的策略器
 * @Author ZhuHJay
 * @Date 2021/9/18 21:01
 */
@Slf4j
@Service
public class MessageUnRead implements MessageStrategy {

    @Autowired
    private MessageService messageService;
    @Autowired
    private GroupMessageBodyService groupMessageBodyService;

    @Override
    public Boolean isUse(int type) {
        return WebSocketSignal.MESSAGE_READ == type;
    }

    @Override
    public void executeHandler(ClientMessage clientMessage,
                               ObjectMapper objectMapper,
                               Map<String, Session> clientMaps,
                               Session mySession) throws Exception {
        log.warn("onMessage -匹配到-> MessageUnRead(消息未读)");

        // 判断是群聊还是私聊
        // 私聊
        if( clientMessage.getFromId() != null ){
            // 进行数据库的修改, 修改完后返回数据信息
            messageService.unReadMessageConvert(clientMessage.getFromId(), clientMessage.getToId());
        }
        // 群聊
        else{
            // 进行数据库的修改
            groupMessageBodyService.unReadMessageConvertById(clientMessage.getUnReadsId());
        }
        // 返回数据, 证明连接没问题, 并且操作成功
        sendMessage(objectMapper, mySession,
                    ResponseMessage.success()
                        .appendData("type", WebSocketSignal.MESSAGE_READ)
                        .appendData("ImMessage", clientMessage)
        );
    }
}
